package com.atguigu.spzx.manager.service.Impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ValidateCodeServiceImpl
 * Package: com.atguigu.spzx.manager.service.Impl
 * Description:
 *
 * @Author 刘强
 * @Create 2024/6/29 16:22
 * @Version 1.0
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        // 1. 生成图形验证码字符串
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);

        String imageValidateCodeStr = circleCaptcha.getImageBase64();
        // 2. 生成验证码的key
        String validateCodeKey = UUID.randomUUID().toString().replaceAll("-", "");
        // 3. 生成验证码的值
        String validateCodeValue = circleCaptcha.getCode();
        // 4. 保存验证码的kev和值到redis中
//        redisTemplate.opsForValue().set(validateCodeKey,validateCodeValue);
        stringRedisTemplate.opsForValue().set("user:login:validateCode:" + validateCodeKey,validateCodeValue,5, TimeUnit.MINUTES);
        // 5. 封装返回值
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey( validateCodeKey);
        // 注意： 图形验证码字符串： 我们需要指定mime类型和编码方式，让浏览器正确解析图形验证码字符串
        validateCodeVo.setCodeValue("data:image/png;base64," + imageValidateCodeStr);
        return validateCodeVo;
    }
}
